<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-form :model="param" ref="publishRef" :rules="publishRules" label-width="0" :validate-on-rule-change="false">
      <el-card class="form_card">
        <span class="_before">基本信息</span>
        <div style="margin:40px 40px 0 40px">
          <el-row style="width:600px;min-width: 400px;">
            <el-col :span="11">
              <el-form-item prop="boxStartCity">
                <div>
                  <redStar />提箱城市
                </div>
                <city-select ref="startCityRef" v-model="param.boxStartCity" :disabled="$route.query?.secondaryEditing || isInfo" :needInfo="true" :cityList="startCityList"
                  @cityId="startCityInfo" style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center;margin-top: 40px; ">
              <svg-icon icon-class="toRight" />
            </el-col>
            <el-col :span="11">
              <el-form-item prop="boxBackCity">
                <div>
                  <redStar />还箱城市
                </div>
                <city-select ref="backCityRef" v-model="param.boxBackCity" :disabled="$route.query?.secondaryEditing || isInfo" :needInfo="true" :cityList="backCityList"
                  @cityId="backCityInfo" style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <span style="color: red;">* </span>
          <span style="font-size: 12px">多选城市不超过10个</span> -->
        </div>
      </el-card>

      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">求租信息</span>
        <div style="margin:40px 40px 0 40px">
          <div style="width:100%">
            <redStar />求租箱规格
          </div>
          <boxPriceList ref="boxPriceListRef" :priceList="param.priceList" :disabled="param.boxStartCity.length == 0 || isInfo"
            :isRent="false" :isOutBox="5" @currency="publishCurrency">
          </boxPriceList>

          <el-form-item prop="payCurrency">
            <div style="width:100%">
              <redStar />可结算币种
            </div>
            <el-checkbox-group v-model="param.payCurrency" :disabled="isInfo">
              <el-checkbox label="人民币（CNY）" value="CNY" :disabled="param.isCheckCNY"/>
              <el-checkbox label="美元（USD）" value="USD" :disabled="param.isCheckUSD"/>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="planPickupDate" style="width:150px;margin-top: 20px;">
            <div>
              <redStar />预计提箱日期
            </div>
            <el-date-picker v-model="param.planPickupDate" :disabled="isInfo" :clearable="false" :editable="false" type="date"
              :size="size" />
          </el-form-item>

          <el-form-item prop="boxUsagePeriod" style="width:220px">
            <div style="width: 100%">
              <redStar />箱使期
            </div>
            <el-input-number v-model="param.boxUsagePeriod" :disabled="isInfo" :controls="false" :min="0" :max="999" :precision="0"
              placeholder="< 1000" style="width: 150px" /> &nbsp;天
          </el-form-item>

          <el-form-item style="width:240px">
            <div>
              <redStar />总求租箱量
            </div>
            <el-input v-model="param.inventory" placeholder="请输入" disabled style="width: 100%">
              <template #append>个</template>
            </el-input>
          </el-form-item>

          <!-- <el-form-item style="width:240px">
            <div>
              <redStar />上架方式
            </div>
            <el-select v-model="param.mode" style="width:100%" placeholder="选择上架方式">
              <el-option v-for="item in param.modeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->

        </div>
      </el-card>
      <el-card  class="marginTop20">
        <span class="_before">发布人</span>
        <el-row align="middle">
          <el-col :offset="2" :span="2" class="text-right">求租箱人&nbsp;&nbsp;&nbsp;</el-col>
          <el-col :span="4" class="text-left"><el-input v-model="nickName" style="width: 240px" disabled placeholder="Please input"/></el-col>
        </el-row>
      </el-card>
      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">图文描述</span>
        <div style="margin:40px 40px 0 40px">
          <!-- <el-form-item prop="mainImgList"> -->
          <el-form-item>
            <div>
              <redStar />主图 <span style="color: #999;">(最多上传6张)</span>
            </div>
            <div style="width:100%">
              <div class="div-box-dark">
                <upload-Img ref="uploadImgRef" :type="0" :urlList="param.showMainImgList" :disabledUpload="isInfo" @uploadSccess="uploadSccess" @uploadRemoveSccess="uploadRemoveSccess"
                  style="width:1000px;height: 1000px;" />
                <p v-if="!isInfo">请上传 png/jpg 主图，大小不能超过3M，建议图片像素高于700*700px</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div>详情描述</div>
            <div style="width:100%">
              <div style="min-height:100px;width: 600px;">
                <div v-for="(mark, index) in param.marks">
                  <el-button v-if="index > 0" :icon="CloseBold" type="info" circle @click="handleClose(index)"
                    style="float: right;width:10px;height:10px"></el-button>
                  <div class="div-box-dark">
                    <el-input v-model="mark.textVal" placeholder="在这里介绍您的集装箱" :disabled="isInfo" type="textarea" rows="2" show-word-limit
                      maxlength="200" style="width: 100%;" />
                    <upload-Img :ref="(el) => handleSetInputMap(el, index)" :disabledUpload="isInfo" @uploadSccess="uploadSccess" :urlList="mark.imgInfo"
                      style="width:1000px;height: 1000px; " :index="index" :type="1"/>
                  </div>
                </div>
                <el-button :icon="Plus" type="info" v-if="!isInfo" size="small" @click="handleAdd">新增描述</el-button>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-form-item v-if="!isInfo">
        <div style="height: 100px;width: 100%;"></div>
        <div v-if="param.isLoading" style="margin:auto;color: chocolate;">数据提交中......</div>
        <div v-else style="margin:auto;">
          <el-button @click="onSave('save')">保存待发布</el-button>
          <el-button v-if="!$route.query.secondaryEditing" type="primary" @click="onSave('putWarehouse')">放入仓库</el-button>
          <el-button type="primary" @click="onSave('publish')">立即发布</el-button>
        </div>
      </el-form-item>

    </el-form>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" :title="param.operate == 'add' ? '新增' : '删除'" width="500">
      <!-- <span>This is a message</span> -->
      <el-input v-if="param.operate == 'add'" v-model="param.addElement"></el-input>
      <span v-else> 确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">
            取消
          </el-button>
          <el-button @click="handleOk">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import redStar from '@/views/components/redStar.vue';
import { Plus, Minus, Delete, CloseBold } from '@element-plus/icons-vue'
import boxPriceList from '@/views/components/boxPriceList'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref, watch, } from 'vue';
import uploadImg from '@/components/upload/img.vue'
import citySelect from '@/components/citySelect'
import { useRoute, useRouter,onBeforeRouteLeave } from 'vue-router';
import orderInfo from '@/store/modules/order'
import { ElMessage,ElMessageBox } from 'element-plus';
import Cookies from "js-cookie";
import { agentSubmit, agentTobeReleased,agentInWarehouse, getBoxNum, getBoxInfo, } from '@/api/boxRent'
const router = useRouter();
const $route = useRoute();
const nickName = computed(()=>{
  return JSON.parse(Cookies.get("User-Info"))?.nickname
})
//路由守卫 关闭菜单执行
// onBeforeRouteLeave((to, from, next) => {
//   publishRef.value.resetFields()
//   next();
// });
let param = reactive({
  // priceList: [{ boxType: 5, boxCondition: 5, unitPrice: 0, totalWeight: "30480/32500", inventory: 0, currency: 'CNY' }],
  priceList: [{ boxCondition: 5, boxType: 5,currency: 'CNY',inventory: 0,  totalWeight: "30480/32500KG",unitPrice: 1, inventoryMax: 0  }],
  planPickupDate: new Date(),
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: 5, label: '40HQ', },
    { value: 10, label: '40GP', },
    { value: 15, label: '20HQ', },
    { value: 20, label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '5', label: '全新', },
  ],
  boxSize: '40HQ',
  boxCase: ['fit'],
  loading: false,
  boxSizeHistory: {}, // eg:{40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  totalWeight: 1,
  boxUsagePeriod:"60",
  weightOptions: [
    { value: 1, label: '30480' },
    { value: 2, label: '32500' },
  ],
  mode: 5, //上架方式
  modeList: [
    { value: 5, label: '立即上架' },
    { value: 10, label: '放入仓库' },
  ],
  marks: [{ textVal: '' }],
  period: '',
  showMainImgList: [],
  caseList: [
    { value: 'fit', label: '适货' },
    { value: 'nextNew', label: '次新' },
    { value: 'allNew', label: '全新' },
    { value: 'mix', label: '混提' },
  ],
  sizeList: [
    { value: '40HQ', label: '40HQ' },
    { value: '40GP', label: '40GP' },
    { value: '20HQ', label: '20HQ' },
    { value: '20GP', label: '20GP' },
  ],
  boxStartCity: [],
  boxBackCity: [],
  boxStartCityData: [],
  boxBackCityData: [],
  startCityOptions: [],
  backCityOptions: [],
  dialogVisible: false,
  operate: '',
  addElement: '',
  addType: 'case', // case,size
  overdueFeeDay: 0,
  payCurrency:['CNY'], //可结算币种
  isCheckCNY:true, // 可结算币种默认选中
  isCheckUSD:false
})


const startCityList = ref([])
const backCityList = ref([])
const editId = ref(null)
const isInfo=ref(false)
onActivated(() => {
  const rowData = orderInfo().rowData
  if (!rowData) return

  showData(rowData)
})

const showData = async (rowData: any) => {
  if (!rowData) return
  if(rowData?.isInfo){
    isInfo.value=rowData.isInfo
  }
  editId.value = rowData.id
  if (editId.value) {
    await getBoxInfo(editId.value).then(async (res: any) => {
      const val = res.data
      //城市展示  
      startCityList.value = [{ value: val.carryCityId, label: val.carryCityName, countryId: val.carryCountryId, countryCName: val.carryCountryName }]
      backCityList.value = [{ value: val.returnCityId, label: val.returnCityName, countryId: val.returnCountryId, countryCName: val.returnCountryName }]
      param.boxStartCity = val.carryCityId
      param.boxBackCity = val.returnCityId
      //箱型箱况  
      param.priceList = val.releaseRentPriceList.map(item => {
        return {
          boxType: item.boxType,
          boxCondition: item.boxCondition,
          unitPrice: item.unitPrice,
          totalWeight: item.totalWeight,
          inventory: item.inventory,
          currency: item.currency
        }
      })

      //其他
      param.planPickupDate = val.planPickupDate
      param.boxUsagePeriod = val.boxUsagePeriod
      // param.mode = val.groundingMethod
      param.isLoading = false
      param.marks = JSON.parse(val.detailFileList) || []
      // param.remark = val.remark
      param.showMainImgList = JSON.parse(val.mainFileList)
      param.mainImgList = JSON.parse(val.mainFileList) // 校验

    })
  }

  if (!editId.value) {
    clearData()
  }
}
//清空数据
const clearData = () => {
  param.priceList = [{ boxType: 5, boxCondition: 5, unitPrice: 0, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }]
  editId.value = null
  // publishRef.value.resetFields()
  param.boxStartCity=[]
  param.boxBackCity=[]
  param.boxStartCityData=[]
  param.boxBackCityData=[]
  param.startCityOptions=[]
  param.backCityOptions=[]
  param.dialogVisible=false
  param.operate= ''
  param.addElement= ''
  param.addType= 'case' // case,size
  param.overdueFeeDay= 0
  param.payCurrency=['CNY']//可结算币种
  param.isCheckCNY=true // 可结算币种默认选中
  param.isCheckUSD=false
  param.showMainImgList=[]
  param.marks= [{ textVal: '' }]
  startCityList.value=[]
  backCityList.value=[]
}

// 获取城市和库存
const startCityInfo = (id: any, data: any) => {
  param.boxStartCity = id
  param.boxStartCityData = data

}
const backCityInfo = (ids: any, data: any) => {
  param.boxBackCity = ids
  param.boxBackCityData = data
}

//总库存
param.inventory = computed(() => {
  let num = 0
  if (param.priceList) {
    param.priceList.forEach((el: any) => {
      num += parseInt(el.inventory)
    })
  }
  return num
})


// marks
const handleClose = (val: any) => {
  param.marks.splice(val, 1)
}
const handleAdd = (val: any) => {
  param.marks.push({ textVal: '' })
}

const handleOk = () => {
  param.dialogVisible = false
  if (param.operate == 'add') {
    if (param.addType == 'case') {
      let index = param.caseList.length
      param.caseList.push({ value: 'addElement' + index, label: param.addElement })
    }
    if (param.addType == 'size') {
      param.sizeList.push({ value: param.addElement, label: param.addElement })
    }
    param.addElement = ''
  }
  if (param.operate == 'delete') {
    if (param.addType == 'size') {// param.boxSize
      const index = param.sizeList.findIndex((item: any) => {
        return item.value == param.boxSize
      })
      if (index != -1) {
        param.sizeList.splice(index, 1)
      }
    }
    if (param.addType == 'case') {//param.boxCase
      param.boxCase.map((val: any) => {
        let index = param.caseList.findIndex((item: any) => {
          return item.value == val
        })
        if (index != -1) {
          // indexList.push(index)
          param.caseList.splice(index, 1)
        }
      })
    }
  }
}
// 主图信息
const picturesGroup = reactive({ 
  hostGraph:[],
  detailImage:[]

})
//上传主图
//删除图片信息
const uploadRemoveSccess = (data: any) => { //
  param.mainImgList = data
  const array = picturesGroup.hostGraph
  picturesGroup.hostGraph = []
  for (const iterator of array) {
    if(iterator.uid != data.uid){
      picturesGroup.hostGraph.push(iterator)
    }
  }
}
//上传图片信息
const uploadSccess = (row) =>{
  if(row.type == 1){
    picturesGroup.detailImage.push(row)
  }else if(row.type == 0){
    picturesGroup.hostGraph.push(row)
  }
}

//mainImgList
const validateMainImgList = (rule: any, value: any, callback: any) => {
  if (value) {
    const length = value.length
    if (length < 1) {
      callback(new Error('不能为空'))
    } else {
      callback()
    }
  } else {
    callback(new Error('不能为空2'))
  }
}
const publishRules = {
  boxBackCity: [{ required: true, trigger: "change", message: "不能为空" }],
  boxStartCity: [{ required: true, trigger: "change", message: "不能为空" }],
  boxUsagePeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  planPickupDate: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  mainImgList: [
    { required: true, validator: validateMainImgList, trigger: 'blur' },
  ],
}

const uploadImgRef = ref()
const uploadRef = {}
const handleSetInputMap = (el, index: number) => {
  if (el) {
    uploadRef[`imgRef${index}`] = el;
  }
};
// 保存/发布
const { proxy } = getCurrentInstance();
const onSave = async (opr: any) => {  //save 保存待发布  pulish 立即发布
  param.isLoading = true
  // let imgList = await uploadImgRef.value.submitUpload()
  let imgList = picturesGroup.hostGraph
  let mainImg = param.showMainImgList
  if(mainImg) { // 新主图和原主图 list合并
    mainImg.forEach((item: any) => {
      imgList.push(item)
    })
  }

  let imgListInfo = []
  // param.marks [{textVal: '我是备注132', imgInfo: [{name:'',url:''}]},{textVal: '我是备注132', imgInfo: [{name:'',url:''}]}]
  for (let i = 0; i < param.marks.length; i++) { // 循环遍历  注意 forEach使用 会数据丢失
    let el = param.marks[i]
    // let imgs = await uploadRef[`imgRef${i}`].submitUpload()
    let imgs = []
    if(picturesGroup.detailImage){
      picturesGroup.detailImage.forEach((item: any) => {
        if(item.index == i){
          imgs.push(item)
        }
      })
    }
    if (el.imgInfo) { // 新副图和原副图 list合并
      el.imgInfo.forEach((item: any) => {
        imgs.push(item)
      })
    }
    imgListInfo.push({ textVal: el.textVal, imgInfo: imgs })
  }
  if(picturesGroup.hostGraph.length <= 0) {
    param.isLoading = false
    return ElMessage.warning("主图不能为空，请上传主图")
  }

  let template = {
    "planPickupDate": param.planPickupDate,
    "boxUsagePeriod": param.boxUsagePeriod,
    "groundingMethod": param.mode,
    "mainFileList": JSON.stringify(imgList), //主图,
    "detailFileList": JSON.stringify(imgListInfo), //详情信息 textVal
    "payCurrency":param.payCurrency.join(","),//可结算币种 
    "releaseRentPriceList": param.priceList
  }

  if (editId.value) {
    const startCity = startCityList.value[0]
    const backCity = backCityList.value[0]
    let obj = {
      "id": editId.value,
      "carryCityId": startCity.value,
      "carryCityName": startCity.label,
      "carryCountryId": startCity.countryId,
      "carryCountryName": startCity.countryCName,
      "returnCityId": backCity.value,
      "returnCityName": backCity.label,
      "returnCountryId": backCity.countryId,
      "returnCountryName": backCity.countryCName,
    }
    Object.assign(template, obj)
  }

  if (param.boxStartCityData?.id) {
    const startCity = param.boxStartCityData
    let obj = {
      "carryCityId": startCity.id,
      "carryCityName": startCity.cityCName,
      "carryCountryId": startCity.countryId,
      "carryCountryName": startCity.countryCName
    }
    Object.assign(template, obj)
  }
  if (param.boxBackCityData?.id) {
    const backCity = param.boxBackCityData
    let obj = {
      "returnCityId": backCity.id,
      "returnCityName": backCity.cityCName,
      "returnCountryId": backCity.countryId,
      "returnCountryName": backCity.countryCName,
    }
    Object.assign(template, obj)
  }

  if (opr == 'save') { //保存待发布
    await agentTobeReleased(template).then((res: any) => {
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if(opr == 'putWarehouse'){ //放入仓库
    await agentInWarehouse(template).then((res: any) =>{
      console.log('放入仓库',res)
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if (opr == 'publish') { //立即上架
    console.log("templatetemplate",template)
    proxy.$refs.publishRef.validate(valid => {
      if (!valid) return param.isLoading = false
      agentSubmit(template).then((res: any) => {
        param.isLoading = false
        router.back()
      }).catch((err: any) => {
        setTimeout(() => {
          param.isLoading = false
        }, 2000)
      })
    })
  }

}

//根据租箱规格选择的币种 筛选可结算币种
const publishCurrency = (val: any) => {
  param.payCurrency.length = 0 
  param.payCurrency.push(val)
  if(val =="CNY"){
    param.isCheckCNY = true
    param.isCheckUSD = false
  }else if(val == "USD"){
    param.isCheckCNY = false
    param.isCheckUSD = true
  }
}

//功能函数
const handleAddPriceList = () => {
  const price = param.priceList[param.priceList.length - 1] //新增 默认copy最后一行的数据
  const data = JSON.parse(JSON.stringify(price))
  param.priceList.push(data)
}

const handleDeletePriceList = (index: any) => {
  if (param.priceList.length == 1) {
    ElMessage.error('至少保留一个')
    return
  }
  param.priceList.splice(index, 1)
}

let initialData: any;
onMounted(() => {
  initialData = structuredClone(JSON.parse(JSON.stringify(param)))
})
import { bus } from '@/store/eventBus'
import _ from 'lodash'
// 组件B
bus.on('call-b', () => {
  if(!_.isEqual(initialData,param) && !isInfo.value){
    ElMessageBox.confirm('存在未保存数据，确定离开吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessageBox.close();
        bus.emit('b-response', 'next')
      }).catch(() => {
        ElMessageBox.close();
        bus.emit('b-response', 'stop')
      })
  }else{
    ElMessageBox.close();
    bus.emit('b-response', 'next')
  }
})



</script>

<style lang="scss"  scoped>
.tagCard {
  background-color: WhiteSmoke;
  border: 1px solid #DCDCDC;
  border-size: border-box;
  padding: 10px;
  border-radius: 5px;
  margin-right: 5px
}
</style>